﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace Reservoir.WebSite
{
    /// <summary>
    /// vCode 的摘要说明
    /// </summary>
    public class vCode : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            //定义验证码数字或者字母
            string content = "35420135351351wdadsvhbjdsvbhjdsbvhjdvbhjdsfbhjdsvbhdsvbhjdsvgfuergfeu";
            //实例化随机对象
            Random r = new Random();
            StringBuilder buile = new StringBuilder();
            //存储生成验证码
            string vCode = "";
            //循环生成验证码
            for (int i = 0; i < 4; i++)
            {
                //获取每次生成的单个字符
                vCode += content.Substring(r.Next(0, content.Length), 1);
            }
            //将验证码追加到生成器中
            buile.Append(vCode);
            //将随机生成的验证码储存起来
            context.Session["vali"] = vCode;


            //空白图片
            Bitmap bit = new Bitmap(100, 30);
            //创建一个新的图片
            Graphics g = Graphics.FromImage(bit);
            //填充背景颜色
            g.FillRectangle(Brushes.Wheat, new Rectangle(0, 0, bit.Width, bit.Height));
            //设置各种字体以及每个字体单独的颜色
            for (int i = 0; i < vCode.Length; i++)
            {
                //随机生成颜色
                Color color = Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255));
                //设置颜色
                SolidBrush s = new SolidBrush(color);
                //设置每个字的坐标
                PointF f = new PointF(i * 25 + 10, r.Next(1, 10));
                //绘制字符在图片上面
                g.DrawString(vCode[i].ToString(), new Font("微软圆滑", 16), s, f);
            }
            for (int i = 0; i < 4; i++)
            {
                //随机生成颜色
                Color color = Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255));
                //绘制一条线
                g.DrawLine(new Pen(color, 1), new Point(r.Next(0, 100), r.Next(0, 30)), new Point(r.Next(0, 100), r.Next(0, 30)));
            }
            //将画好的图片输出到流中，并且设置图片的格式
            bit.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            //释放图片资源
            bit.Dispose();
            g.Dispose();
            //结束响应
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}